package com.mediacloud.app.newsmodule.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import androidx.annotation.Nullable;
import android.util.Log;

import com.mediacloud.app.user.net.SSLSocketClient;
import com.loopj.android.http.RequestParams;
import com.mediacloud.app.assembly.common.MD5Encoder;
import com.mediacloud.app.assembly.interfaces.LoadNetworkBack;
import com.mediacloud.app.assembly.util.ConfiguRation;
import com.mediacloud.app.assembly.util.FileUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.drama.DramaVideoHelper;
import com.mediacloud.app.newsmodule.model.DownLoad;
import com.mediacloud.app.newsmodule.model.OnDownloadProcessListener;
import com.mediacloud.app.newsmodule.utils.DownloadDB;
import com.mediacloud.app.newsmodule.utils.MathTool;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.reslib.util.HTTPClient;
import com.mediacloud.app.reslib.util.RequestParamsX;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;

public class DownloadManagers extends Service {

    ArrayList<DownLoad> mQueue = new ArrayList<DownLoad>();
    DownloadDB mDownloadDB;
    OnDownloadProcessListener mOnDownloadProcessListener;
    Context mContext;

    ConfiguRation mConfiguRation;
    public String errInfo = "";

    public void setOnDownloadProcessListener(OnDownloadProcessListener listener) {
        //Log.i("test", " onProcess ?setOnDownloadProcessListener");
        mOnDownloadProcessListener = listener;
    }


/*    public void onStartCommand(Context context) {
        mContext = context;
        mDownloadDB = new DownloadDB(mContext);
        http = new HttpUtils();
        http.configRequestThreadPoolSize(5);
        ArrayList<DownLoad> data = mDownloadDB.getDownLoadData(DownloadDB.ING_TABLE_NAME_);
        if (data != null) {
            mQueue.addAll(data);
        }
        toDownLoad();
    }*/

    public void toDownLoad() {
        //Log.i("test", " onProcess ?toDownLoad");
       /* if(handler!=null)
        {
            Log.i("test","onProcess:handler.isPase?"+handler.isPaused() +"   handler.isCancel:"+handler.isCancelled());
          *//*  if(!handler.isPaused())
            {
                return;
            }*//*

        }*/
        isInit = true;
        try {
            if (mQueue.size() > 0) {
                if (mQueue.get(0).getTypes().equals("0")) {
                    getViedeoInfo(mQueue.get(0).getUrl(), mQueue.get(0).getTagId());
                } else {
                    downLoad(mQueue.get(0));
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }

    private void getViedeoInfo(String article_id, String catalog_id) {
        //Log.i("test", " onProcess ?getDramaVideoInfo");
        String interfaces = "api/content/drama-info";
        RequestParams param = new RequestParamsX();
        param.put("article_id", article_id);
        param.put("catalog_id", catalog_id);

//        param.put("api_version", "1.2.3");
        HTTPClient helper = new HTTPClient();
        helper.getNetData(new LoadNetworkBack<DramaVideoHelper>() {

            @Override
            public void Success(DramaVideoHelper result) {


                if (result.mUrls == null || !result.state) {
                    mQueue.get(0).setTagId("-1");
                    mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                    mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                    mQueue.remove(0);
                    if (mOnDownloadProcessListener != null) {
                        mOnDownloadProcessListener.onProcess("-1", 111, 111, null);
                    }
                    toDownLoad();


                    return;
                }
                //Log.i("test", "result.mUrls.mp4Address.size():" + result.mUrls.mp4Address.size());
                if (result.mUrls.mp4Address.size() != 0 && mQueue.size() != 0) {

                    int rate = Integer.parseInt(mQueue.get(0).getRate());
                    if (result.mUrls.mp4Address.size() >= (rate + 1) && mQueue.size() > 0) {
                        mQueue.get(0).setUrl(result.mUrls.mp4Address.get(rate).url);
                        mQueue.get(0).setTypes("1");
                        mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        mDownloadDB.saveData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        downLoad(mQueue.get(0));
                    } else {


                        mQueue.get(0).setUrl(result.mUrls.mp4Address.get(result.mUrls.mp4Address.size() - 1).url);
                        mQueue.get(0).setTypes("1");
                        mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        mDownloadDB.saveData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        downLoad(mQueue.get(0));
                    }
                } else {

                    if (mQueue.size() > 0) {
                        mQueue.get(0).setTagId("-1");
                        mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                        mQueue.remove(0);

                    } else {

                    }
                    if (mOnDownloadProcessListener != null) {
                        mOnDownloadProcessListener.onProcess("-1", 111, 111, null);
                    }
                    toDownLoad();

                }
            }

            @Override
            public void Failure(Object obj) {

            }

            @Override
            public void otherData(String result) {

            }
        }, DataInvokeUtil.ServerURL + interfaces, new DramaVideoHelper(), param);
    }

    public boolean isInit = false;

    public void addQueue(DownLoad item) {
       /* Log.i("test", "mDownloadDB:" + mDownloadDB);
        Log.i("test", "item:" + item);*/
      // MathTool.isStart = false;
        checkIsDownLoad();
        //Log.i("test", " onProcess ?addQueue");
        if (mDownloadDB == null) {
            mDownloadDB = new DownloadDB(mContext);
        }
        mDownloadDB.saveData(item, DownloadDB.ING_TABLE_NAME_);
        mQueue.add(item);

        if (mQueue.size() == 1) {
            toDownLoad();
        }


    }

    public ArrayList<DownLoad> getQueues() {
        return mQueue;
    }

    boolean isHaveDown;

    public void addQueues(ArrayList<DownLoad> datas) {
        //Log.i("test", " onProcess ?addQueues");
    //    MathTool.isStart = false;
        checkIsDownLoad();
        isHaveDown = false;
        isHaveDown = mQueue.size() == 0;
        if (mDownloadDB == null) {
            mDownloadDB = new DownloadDB(mContext);
        }
        for (int i = 0; i < datas.size(); i++) {
            mDownloadDB.saveData(datas.get(i), DownloadDB.ING_TABLE_NAME_);
        }
        mQueue.addAll(datas);
        if (mQueue.size() > 0 && isHaveDown) {
            toDownLoad();
        }
    }
    /*public HttpHandler handler;
    HttpUtils http;*/

    public boolean onDownloadPause() {
        //Log.i("test", " onProcess ?onDownloadPause");
        if (handler != null) {
            //handler.cancel();

            if (!handler.isCancelled()) {
                handler.cancel();
                return true;
            }
        }
        return false;
    }

    public boolean onDownloadResum() {
        //Log.i("test", " onProcess ?onDownloadResum");
        if (handler != null) {
            if (handler.isCancelled()) {
                toDownLoad();
                return true;
            }
        }
        return false;
    }

    OnPauseListner mOnPauseListner;

    public void checkIsDownLoad() {

        if (MathTool.isStart&&mQueue.size()>0) {

            toDownLoad();
        }
        MathTool.isStart = false;
    }

    public void setOnPauseListner(OnPauseListner listner) {
        mOnPauseListner = listner;
    }

    public interface OnPauseListner {

        void OnPause();

        void OnResum();

    }

    String currentDown = "";
    public Callback.Cancelable handler;

    private void downLoad(DownLoad item) {
        currentDown = item.getId();
        //Log.i("test", " onProcess ?download downLoad exe");
        org.xutils.http.RequestParams params = new org.xutils.http.RequestParams(item.getUrl());
        params.setSslSocketFactory(SSLSocketClient.getSSLSocketFactory());
        params.setAutoRename(true);//断点下载
        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/appfactory/videocach/" + MD5Encoder.encode(item.getUrl() + item.getNames() + item.getId()) + ".mp4";
        params.setSaveFilePath(sdPath);//
        params.setExecutor(new PriorityExecutor(2,true));//自定义线程池,有效的值范围[1, 3], 设置为3时, 可能阻塞图片加载.
        params.setCancelFast(true);//是否可以被立即停止.
        params.setSslSocketFactory(SSLSocketClient.getSSLSocketFactory());
        handler = x.http().get(params, new Callback.ProgressCallback<File>() {
            @Override
            public void onSuccess(File file) {

                //Log.i("test", "xutils:onSuccessfile is null?:" + file.length());
                if (mQueue.size() > 0) {
                    mQueue.get(0).setTagId("1");
                    mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                    mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                    mQueue.remove(0);
                    if (mOnDownloadProcessListener != null) {
                        mOnDownloadProcessListener.onProcess("-1", 111, 111, null);
                    }
                    toDownLoad();

                }

                isDownload = false;
            }

            @Override
            public void onError(Throwable throwable, boolean b) {
                //Log.i("test", "xutils:onError--onError?:" + throwable.toString());
            /*   if (mQueue.size() > 0) {

                        mQueue.get(0).setTagId("-2");
                       mDownloadDB.deleteData(mQueue.get(0), DownloadDB.ING_TABLE_NAME_);
                        mDownloadDB.saveData(mQueue.get(0), DownloadDB.Complete_TABLE_NAME_);
                        mQueue.remove(0);
                        if(mOnDownloadProcessListener!=null) {
                            mOnDownloadProcessListener.onProcess("-1", 111, 111, null);
                        }
                   toDownLoad();


                }else
                {

                    handler.cancel();
                    handler=null;

                }*/
                isDownload = false;
                errInfo = getResources().getString(R.string.access_resource_failed);
                handler.cancel();
                mConfiguRation.shardBoolean("isPause", true);
                if (mOnPauseListner != null) {
                    mOnPauseListner.OnPause();
                }
                // handler=null;
            }

            @Override
            public void onCancelled(CancelledException e) {
                isDownload = false;
                if (mOnPauseListner != null) {
                    mOnPauseListner.OnPause();
                }

            }

            @Override
            public void onFinished() {
                isDownload = false;
                isInit = false;
            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {
                isInit = false;
                //Log.i("test", " onProcess ?download onStart");
                errInfo = "";
                if (mOnPauseListner != null) {
                    mOnPauseListner.OnResum();
                }
                mConfiguRation.shardBoolean("isPause", false);
                if (mOnDownloadProcessListener != null)
                    mOnDownloadProcessListener.onProcess("-2", 0, 0, null);

            }

            @Override
            public void onLoading(long l, long l1, boolean b) {
                //Log.i("test", "onLoading ?l?=" + l + "  l1?=" + l1);
                isDownload = true;
                try {
                    if (mOnDownloadProcessListener != null && mQueue.size() > 0) {
                        mOnDownloadProcessListener.onProcess(mQueue.get(0).getId(), l, l1, null);
                    } else {
                        handler.cancel();

                        //  http=null;*//*
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void deleteIngDown(DownLoad position) {

        if (position.getId().equals(currentDown) && handler != null) {
            handler.cancel();
            //toDownLoad();
        }


        Boolean isDele = FileUtil.delFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/appfactory/videocach/" + MD5Encoder.encode(position.getUrl() + position.getNames() + position.getId()) + ".mp4.tmp");

//        if (isDele) {
//            Log.i("test", "onProcess:ing:position==>delete sucess" + position + "   mQueue  size: " + mQueue.size());
//        }
        mDownloadDB.deleteData(position, DownloadDB.ING_TABLE_NAME_);
        mQueue.remove(position);
        //   toDownLoad();
    }


    private void checkQuenIsNull() {

        if (mQueue.size() < 1) {
            mQueue.addAll(mDownloadDB.getDownLoadData(DownloadDB.ING_TABLE_NAME_));
        }

    }

    @Override
    public void onCreate() {
        super.onCreate();
        mConfiguRation = new ConfiguRation(this);
        //Log.i("test", "onProcess:onCreate");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //Log.i("test", "onProcess:onCreate");

        return serviceBinder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //Log.i("test", "onProcess:onDestroy");

        try {
            if (handler != null)
                handler.cancel();
            mConfiguRation.shardBoolean("isPause", true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    boolean isDownload = false;
    int mStartId = -1;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //Log.i("test", "onProcess:onStartCommand:flags?" + flags + " startId?" + startId);
        mDownloadDB = new DownloadDB(getApplicationContext());

        ArrayList<DownLoad> data = mDownloadDB.getDownLoadData(DownloadDB.ING_TABLE_NAME_);
        if (data != null) {
            mQueue.clear();
            mQueue.addAll(data);
        }
        if (mStartId == -1) {
            mStartId = startId;
            toDownLoad();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    public class DownLoadServiceBinder extends Binder {
        public DownloadManagers getService() {
            return DownloadManagers.this;
        }
    }

    public DownloadManagers() {

    }

    private Binder serviceBinder = new DownloadManagers.DownLoadServiceBinder();
}